package cn.db.tools.dbtools.controller;

import cn.db.tools.dbtools.message.ToastMessage;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.common.io.BaseEncoding;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.Files;
import com.google.common.primitives.Bytes;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DataFormat;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import org.pomo.toasterfx.model.impl.ToastTypes;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ResourceBundle;

/**
 * @author：zooooooooy
 * @date: 2023/8/9 - 18:10
 */
public class ImageToBase64Controller implements Initializable {

    @FXML
    private Button fcButton;

    @FXML
    private AnchorPane anchorPane;

    @FXML
    private ImageView imageView;

    @FXML
    private TextArea base64Text;

    FileChooser fileChooser = new FileChooser();


    @Override
    public void initialize(URL location, ResourceBundle resources) {

        base64Text.setWrapText(true);

        fcButton.setOnAction(event -> {
            fileChooser.setTitle("打开图片");
            File file = fileChooser.showOpenDialog(anchorPane.getScene().getWindow());
            try {
                imageView.setImage(new Image(new FileInputStream(file)));

                // file转base64
                base64Text.setText("data:image/" + Files.getFileExtension(file.getName()) + ";base64," + BaseEncoding.base64().encode(Files.toByteArray(file)));
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        });
    }

    @FXML
    protected void copyTextFieldBase64() {
        Clipboard sc = Clipboard.getSystemClipboard();
        ClipboardContent clipboardContent = new ClipboardContent();
        clipboardContent.put(DataFormat.PLAIN_TEXT, base64Text.getText());

        sc.setContent(clipboardContent);
        // 弹出toast消息
        ToastMessage.getInstance().popMessage("复制成功", ToastTypes.SUCCESS);
    }
}
